import React from "react";

function CommentRes(props) {
    const { comments } = props
    return comments.length ? (
        <ul>
            {comments.map((item) => (
                <li key={item.id}>
                    {/*<span style={{marginRight: '30px'}}>评论人：{`${item.name}+${item.id}`}</span>*/}
                    <div style={{marginRight: '30px'}}>评论人：{item.name}&nbsp;&nbsp;&nbsp;<button>删除</button></div>
                    <span>评论内容：{item.content}</span>
                </li>
            ))}
        </ul>
    ) : (<span className="no-comment">还没有评论，快来评论吧！</span>)
}

class Comment extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            content: '',
            comments: []
        }
    }

    // 处理表单元素值
    handleForm = e => {
        const {name, value} = e.target;
        this.setState({
            [name]: value
        })
    }

    // 提交评论
    sendComment = () => {
        const {name, content, comments} = this.state;

        if(!name.trim() || !content.trim()) {
            alert('请输入内容')
            return;
        }

        const newComment = [{
            id: Math.random(),
            name: name,
            content: content
        }, ...comments];

        this.setState({
            comments: newComment,
            name: '',
            content: ''
        })
    }

    render() {
        const {content, name, comments} = this.state;
        return (
            <div className="box">
                <input onChange={this.handleForm} name="name" value={name} placeholder={'请输入评论人'}/><br/><br/>
                <textarea onChange={this.handleForm} cols="30" rows="10" placeholder="请输入评论内容" value={content} name="content" /><br/>
                <button onClick={this.sendComment}>提交</button><br/><br/>
                <CommentRes comments={comments}/>
            </div>
        )
    }
}

export default Comment;
